package css.sword.util;

import com.alibaba.fastjson.JSONObject;
import css.sword.controller.HelloController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class WpsSecureUtil {

    static Logger log=LoggerFactory.getLogger(WpsSecureUtil.class);

    public static String rootPath = "/opt";

    public static String s_serverUrlSecurityDoc = "http://yun.szoa.sz.gov.cn/securitydoc";
    //账号服务器地址
    public static String s_serverUrlAccount = "http://yun.szoa.sz.gov.cn/account";

    public static String s_secDocHelperPath  = rootPath + "/securitydochelper";

    static String s_permissions = "{\\\"docrights\\\":[{\\\"principalid\\\":\\\"2\\\",\\\"principaltype\\\":2,\\\"operationids\\\":[2,3,4]}]}";

    static String s_templateDir = rootPath + "/template/templatedir";

    //获取权限信息结果文件
    static String s_getPermissionsResultFile = rootPath + "\\testFiles\\getPermissionsResult.txt";

    //修改权限信息结果文件
    static String s_pushPermissionsResultFile = rootPath + "\\testFiles\\pushPermissionsResult.txt";

    static String s_onlineSession = "";
    static Process p;

    //安全文档相关操作
    static enum SecurityDocOP {
        op_isSecurityDoc,                //判断文档是否是安全文档
        op_getSecurityDocGuid,           //获取安全文档的guid
        op_getSecurityDocId,             //获取安全文档在服务器对应的docid
        op_getOnlineSession,             //通过用户名密码获取session
        op_decryptSecurityDoc,           //解密安全文档
        op_createSecurityDoc,            //创建安全文档
        op_fetchDocPermissions,          //获取文档的权限信息
        op_pushDocPermissions            //更新文档的权限信息
    }

    public static int runSecurityDocOperation(String cmd) throws InterruptedException {
        try {
            String outputStr = new String("run command: ") + cmd;
            log.debug(outputStr);
            p = Runtime.getRuntime().exec(cmd);
            int retval = p.waitFor();
            return retval;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //todo
        }
        return -1;
    }

    //判断文档是否是安全文档
    public static boolean isSecurityDoc(String docpath) {
        boolean isSecurityDoc = false;
        try {
            //命令行参数（每个参数以空格隔开）：exe路径   操作类型   文档路径
            String cmdStr = s_secDocHelperPath + " " + WpsSecureUtil.SecurityDocOP.op_isSecurityDoc.ordinal() + " " + docpath;
            int ret = runSecurityDocOperation(cmdStr);
            log.debug(ret+"isSecurityDoc");
            isSecurityDoc = (ret == 0);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(e.toString());
        }
        return isSecurityDoc;
    }

    // 根据ca的token 找到wpssid
    private static String GetSession(String token) {
        String rsp = "";
      //  String urlString = "http://yunselftest.szoa.sz.gov.cn/secure/session/user?token=" + token;
        String urlString = "http://yun.szoa.sz.gov.cn/secure/session/user?token=" + token;
        rsp = HttpClient.doGet(urlString);
        System.out.println("GetSession rsp:" + rsp);
        JSONObject jsonObject = JSONObject.parseObject(rsp);
        String data = jsonObject.getString("data");
        return data;
    }

    //将普通文档转为安全文档
    public static int createSecurityDoc(String srcPlainDocPath, String destSecurityDocPath,String caToken) {
        int result = -1;
        String s_onlineSession=GetSession(caToken);
        try {
            //命令行参数（每个参数以空格隔开）：exe路径    操作类型    模版文件路径    安全服务器地址    用户session  原普通文档路径    生成的安全文档路径
            String cmdStr = s_secDocHelperPath + " " + WpsSecureUtil.SecurityDocOP.op_createSecurityDoc.ordinal() + " " + s_templateDir + " "
                    + s_serverUrlSecurityDoc + " " + s_onlineSession + " " + srcPlainDocPath + " " + destSecurityDocPath;
            result = runSecurityDocOperation(cmdStr);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return result;
    }

    //将安全文档转为普通文档
    public static int decryptSecurityDoc(String srcSecurityDocPath, String destPlainDocPath,String caToken) {
        int result = -1;
        String s_onlineSession=GetSession(caToken);
        try {
            //命令行参数（每个参数以空格隔开）：exe路径    操作类型    模版文件路径    安全服务器地址    用户session  原安全文档路径    生成的普通文档路径
            String cmdStr = s_secDocHelperPath + " " + WpsSecureUtil.SecurityDocOP.op_decryptSecurityDoc.ordinal() + " " + s_templateDir + " "
                    + s_serverUrlSecurityDoc + " " + s_onlineSession + " " + srcSecurityDocPath + " " + destPlainDocPath;
            result = runSecurityDocOperation(cmdStr);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(e.toString());
        }
        return result;
    }

    public static void main(String[] args)
    {
//        System.out.println("main begin...");
//        String outputStr = "";
//
//        //判断文档是否是安全文档
//        String docPath = s_securityDocPath;
//        //String docPath = s_nonSecurityDocPath;
//        if (isSecurityDoc(docPath)) {
//            outputStr = docPath + " is a security doc!";
//            System.out.println(outputStr);
                    //                    AQIC5wM2LY4Sfcw348dMMUrmhGXTYqF6WIs-GbUaDdz_eTo.*AAJTSQACMDEAAlNLABMyMDk4NzgyODUzNjkxNTczNDQ0*,AQIC5wM2LY4SfcxSyt9F0CzXeTBg5vkO4n-oJdOGpl1WXvM.*AAJTSQACMDEAAlNLABQtNDUwOTg3NDA1NzEzMjU5NTI3MQ..*
                            //            AQIC5wM2LY4SfcxSyt9F0CzXeTBg5vkO4n-oJdOGpl1WXvM.*AAJTSQACMDEAAlNLABQtNDUwOTg3NDA1NzEzMjU5NTI3MQ..*

        // System.out.println(GetSession("AQIC5wM2LY4SfcxSyt9F0CzXeTBg5vkO4n-oJdOGpl1WXvM.*AAJTSQACMDEAAlNLABQtNDUwOTg3NDA1NzEzMjU5NTI3MQ..* "));
        System.out.println(GetSession("AQIC5wM2LY4SfcyP4SYJa6cXXJpuj1nZNQynT1V5XP-I3rY.*AAJTSQACMDEAAlNLABIzMzQ5NTE0NDMwMjI4MTg2MzM.*"));

      //
//            //解密安全文档为普通文档
//            String destPlainDocPath = s_nonSecurityDocPath;
//            ret = decryptSecurityDoc(docPath, destPlainDocPath);
//            if (ret == 0) {
//                outputStr = new String("decrypt security doc succeed, result file path is : ") + destPlainDocPath;
//                System.out.println(outputStr);
//            }
//            else {
//                outputStr = new String("decrypt security doc failed");
//                System.out.println(outputStr);
//            }
//
//        }
//        else {
//            outputStr = docPath + " is not a security doc!";
//            System.out.println(outputStr);
//
//            //将普通文档转为安全文档
//            String destSecurityDocPath = s_securityDocPath;
//            int ret = createSecurityDoc(docPath, destSecurityDocPath);
//            if (ret == 0) {
//                outputStr = new String("create security doc succeed, result file path is : ") + destSecurityDocPath;
//                System.out.println(outputStr);
//            }
//            else {
//                outputStr = new String("create security doc failed");
//                System.out.println(outputStr);
//            }
//        }
      }

}
